import re
import htmllib
from Products.CMFPlone import PloneMessageFactory as _
from Products.CMFCore.utils import getToolByName
import threading
import time

def extract(mask, input):
    input = re.search(mask, input, re.IGNORECASE)
    if input:
        return input.group()
    else:
        return ''

def extractMeta(value, input):
    value = extract('<[\w]*meta[^(name)](name)[^=]*=[\'"]+'+value+'[\'"]+[^>]+>', input)
    if value:
        content = extract('content[^=]*=[^"]*["]+[^"]*["]+', value)
        if not content:
            content = extract("content[^=]*=[^']*[']+[^']*[']+", value)
            contentStart = extract("content[^=]*=[^']*[']+", content)
        else:
            contentStart = extract('content[^=]*=[^"]*["]+', content)
        value = content.replace(contentStart, '')[:-1]
        if value:
            return value
    return ''

alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
def incrCharacter(counter):
    if not counter:
        return alphabet[0]
    elif counter[-1] == alphabet[-1]:
        return incrCharacter(counter[0:-1]) + alphabet[0]
    else:
        return counter[0:-1] + alphabet[alphabet.find(counter[-1]) + 1]

def prettyString(input):
    """
    """
    p = htmllib.HTMLParser(None)
    p.save_bgn()
    p.feed(input)
    return unicode(p.save_end(), errors='ignore')
    
def genBox(im):
    height = im.getbbox()[3]
    a6th = im.getbbox()[2]/3
    if a6th > height:
        a6th = height
    return (0, 0, im.getbbox()[2], a6th)

def postPortalMessage(message, context):
    message = _(unicode(message))
    putils = getToolByName(context, 'plone_utils')
    putils.addPortalMessage(message)
    
class ThreadFindIShortURLUnindexed(threading.Thread):

    def __init__(self, context):
        self.context = context
        threading.Thread.__init__(self)

    def run(self):
        time.sleep(1000)
        self.context.findIShortURLUnindexed()